package com.kandinfo.base.security.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kandinfo.base.common.converter.ConverterService;
import com.kandinfo.base.common.dto.ResultDto;
import com.kandinfo.base.common.dto.ResultDtoFactory;
import com.kandinfo.base.common.dto.widget.DataTablesResponseDto;
import com.kandinfo.base.security.domain.Role;
import com.kandinfo.base.security.domain.User;
import com.kandinfo.base.security.domain.UserRole;
import com.kandinfo.base.security.dto.RoleDto;
import com.kandinfo.base.security.dto.RoleSearchDto;
import com.kandinfo.base.security.service.RoleService;
import com.kandinfo.base.security.service.UserRoleService;
import com.kandinfo.base.security.service.UserService;

/**
 * 
* Class Name: RoleController
* Description: RoleController
* @author qianqiao
*
 */
@Controller
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private UserService userService;
    
    @RequestMapping(value = "/role", method = RequestMethod.GET)
    public String home(Model model) {
        model.addAttribute("roleList", roleService.findAll());
        return "sys/role_list";
    }

    /*
     * 获得所有的Role
     */
    @RequestMapping(value = "/role/getAll", method = RequestMethod.GET)
    @ResponseBody
    public List<Role> getAll() {
        return roleService.findAll();
    }

    @RequestMapping(value = "/role/searchbyCon", method = RequestMethod.POST)
    @ResponseBody
    public DataTablesResponseDto<RoleDto> searchByCon(@RequestBody RoleSearchDto request) {
        DataTablesResponseDto<RoleDto> resp = roleService.searchByCon(request);
        resp.setEcho(request.getEcho());
        return resp;
    }

    @RequestMapping(value = "/role/doDelete/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public ResultDto doDelete(@PathVariable("id") Long id) {
        String message = "";
        List<UserRole> userRoleList = userRoleService.findByRoleId(id);
        if (userRoleList.size() == 0) {
            roleService.delete(id);
            message = "角色删除成功!";
        } else if (userRoleList.size() > 0) {
            message = "此角色下有用户，不能删除!";
        } else {
            message = "未知错误";
        }
        return ResultDtoFactory.toAck(message);
    }

    @RequestMapping(value = "/role/toEdit/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Role toEdit(@PathVariable("id") Long id) {
        return roleService.findById(id);
    }

    @RequestMapping(value = "/role/doAdd", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto doAdd(@RequestBody RoleDto roleDto) throws Exception {
        String roleName = roleDto.getRoleName();
        if (StringUtils.isBlank(roleName)) {
            return ResultDtoFactory.toNack("角色名字不能为空");
        }

        // 去除角色名称空格
        roleName = roleName.replaceAll(" ", "");
        roleDto.setRoleName(roleName);

        Role role = ConverterService.convert(roleDto, Role.class);
        if (!CollectionUtils.isEmpty(roleService.checkName(-10L, roleName))) {
            return ResultDtoFactory.toNack("角色名字重复，请重新输入！");
        }
        role.setCreateTs(new Date());

        roleService.save(role);
        return ResultDtoFactory.toAck("角色创建成功");
    }

    @RequestMapping(value = "/role/doEdit/{id}", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto doEdit(@PathVariable("id") Long id, @RequestBody RoleDto roleDto) throws Exception {
        Role role = roleService.findById(id);
        String roleName = roleDto.getRoleName().replaceAll(" ", "");
        if (!CollectionUtils.isEmpty(roleService.checkName(id, roleName))) {
            return ResultDtoFactory.toNack("角色名字重复，请重新输入！");
        }
        role.setId(id);
        role.setRoleName(roleDto.getRoleName());
        role.setRoleDesc(roleDto.getRoleDesc());
        roleService.save(role);
        return ResultDtoFactory.toAck("角色更新成功");
    }
    @RequestMapping(value = "/role/detail/{id}" , method = RequestMethod.GET)
    @ResponseBody
    public List<User> getDetail(@PathVariable("id") Long id){
        List<User> userList=new ArrayList<User>();
        List<UserRole> userRoleList=userRoleService.findByRoleId(id);
        if(CollectionUtils.isEmpty(userRoleList)){
            return userList;
        }
        for(int i=0;i<userRoleList.size();i++){
            Long userId=userRoleList.get(i).getUserId();
            User user=userService.findUserById(userId);
            userList.add(user);
        }
        return userList;
    }
}
